package com.wayne.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wayne.security.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 账号密码登陆过滤器
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
  @Autowired
  SessionRegistry sessionRegistry;

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (!request.getMethod().equals("POST")) {
      throw new AuthenticationServiceException(
          "Authentication method not supported: " + request.getMethod());
    }
    String verify_kaptcha = (String) request.getSession().getAttribute("kaptcha");
    if (!Objects.isNull(request.getContentType()) && request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
      Map<String, String> loginData = new HashMap<>();
      try {
        loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
      } catch (IOException e) {
      } finally {
        String kaptcha = loginData.get("kaptcha");
        checkCode(kaptcha, verify_kaptcha);
      }
      String username = loginData.get(getUsernameParameter());
      String password = loginData.get(getPasswordParameter());
      if (username == null) {
        username = "";
      }
      if (password == null) {
        password = "";
      }
      username = username.trim();
      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
          username, password);
      setDetails(request, authRequest);
      User principal = new User();
      principal.setUsername(username);
      sessionRegistry.registerNewSession(request.getSession(true).getId(), principal);
      return this.getAuthenticationManager().authenticate(authRequest);
    } else {
      checkCode(request.getParameter("kaptcha"), verify_kaptcha);
      Authentication authentication = super.attemptAuthentication(request, response);
      sessionRegistry.registerNewSession(request.getSession(true).getId(), authentication.getPrincipal());
      return authentication;
    }
  }

  public void checkCode(String kaptcha, String verify_kaptcha) {
    if (kaptcha == null || verify_kaptcha == null || "".equals(kaptcha) || !verify_kaptcha.toLowerCase().equals(kaptcha.toLowerCase())) {
      //验证码不正确
      //throw new AuthenticationServiceException("验证码不正确");
    }
  }
}

